import json
import os
import pandas as pd


# 将DataFrame解析为列表
def parse_csv(df):
    data = []
    for index, row in df.iterrows():
        ep_zone = float(row['ep_zone'])
        p = float(row['p'])
        h = int(row['h'])
        m = int(row['m'])
        data.append([ep_zone, p, h, m])
    return data


# 创建滑动窗口
def create_sliding_windows(data, window_size, num_windows , num_predict):
    windows = []
    windows_prediction = []
    for i in range(min(len(data) + 1 - window_size - num_predict, num_windows)):
        start_index = i
        end_index = start_index + window_size
        window = data[start_index:end_index]
        windows.append(window)
        window_prid = data[end_index : end_index + num_predict]
        windows_prediction.append(window_prid)

    return windows, windows_prediction


# 将数据转换为JSON格式
def data_to_json(windows, id):
    result = {"id": id, "data": windows}
    return json.dumps(result, indent=4)


# 主函数
def main():
    file_path = "02500005_5min0404-0408.csv"

    # 1 读取原始数据
    csv_data = pd.read_csv(file_path)

    # 新增两列，提取月份和小时值
    csv_data['data_time'] = pd.to_datetime(csv_data['data_time'])
    csv_data['m'] = csv_data['data_time'].dt.month
    csv_data['h'] = csv_data['data_time'].dt.hour

    # 解析CSV数据
    data = parse_csv(csv_data)

    # 定义滑动窗口大小和数量
    window_size = 72  # 示例中以12为窗口大小，你可以根据需要修改这个值
    num_windows = 600  # 示例中创建12个滑动窗口，你可以根据需要修改这个值
    num_predict = 36

    base_path = f"data\minuts5\step{window_size}\output"

    # 创建滑动窗口
    windows,windows_predict = create_sliding_windows(data=data, window_size=window_size, num_windows=num_windows,num_predict=num_predict)

    for i in range(len(windows)):
        # 转换为JSON格式
        json_output = data_to_json(windows[i], f"00{int(window_size/36)}")
        json_output2 = data_to_json(windows_predict[i], f"00{int(window_size/36)}")


        file_name = f"{base_path}_{i}"

        # 输出路径
        out_put_path = f"{file_name}.txt"
        os.makedirs(os.path.dirname(out_put_path), exist_ok=True)
        # 将JSON数据写入txt文件
        with open(out_put_path, "w") as f:
            f.write(json_output)


        # 输出路径
        out_put_path2 = f"{file_name}_predict{num_predict}.txt"
        os.makedirs(os.path.dirname(out_put_path2), exist_ok=True)
        # 将JSON数据写入txt文件
        with open(out_put_path2, "w") as f:
            f.write(json_output2)



if __name__ == "__main__":
    main()